<template>
  <div class="app-container">
  <!--校区s数据-->
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="城市" prop="city">
       <el-select v-model="queryParams.city" placeholder="请选择" clearable filterable size="small" >
         <el-option
           v-for="dict in ownCity"
           :key="dict.key"
           :label="dict.value"
           :value="dict.key"
         />
       </el-select>
      </el-form-item>
      <el-form-item label="校区名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="状态"
          clearable
          size="small"
        >
          <el-option :key="999" :label="'全部'" :value="null" />
           <el-option :key="1" :label="'启用'" :value="1" />
           <el-option :key="0" :label="'关闭'" :value="0" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="创建时间">
        <el-date-picker
                v-model="dateRange"
                size="small"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
            v-hasPermi="['system:school:add']"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:school:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:school:remove']"
        >删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:school:export']"
        >导出</el-button> -->
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="50" align="center" /> -->
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="校区名称" align="center" prop="name" />
      <el-table-column label="校区ID" align="center" prop="id" />
      <el-table-column label="城市" align="center" prop="city" />
      <el-table-column label="排序" align="center" prop="sortNum" :show-overflow-tooltip="true" />
      <el-table-column label="校区总人数" sortable align="center" prop="personNum"  width="120"/>
      <el-table-column label="站点数" align="center" prop="siteNum" />
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <div class="dian" :class="scope.row.status == 1 ? 'dian_kai':''" ></div><span>{{scope.row.status === 1?'启用':'关闭'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="insertOperator" />
      <el-table-column label="操作" align="center" width="220">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            v-hasPermi="['system:school:details']"
            @click="handleUpdate(scope.row, '详情')"
          >查看</el-button>
          <el-button
            size="mini"
            type="success"
            v-hasPermi="['system:school:edit']"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            v-hasPermi="['system:school:remove']"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="16">
            <el-form-item label="校区名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="所在城市" prop="city">
                <!-- <el-select v-model="form.city" placeholder="请选择" clearable filterable size="small" >
                  <el-option
                    v-for="dict in cityOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.label"
                  />
                </el-select> -->
                <el-cascader
                  ref="cityHandle"
                  v-model="form.cityData"
                  :options="cityOptions"
                  :props="{ multiple:false, value: 'label',label: 'label' }"
                  @change="cityChange"
                  clearable></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="所属部门" prop="deptId">
                <el-select v-model="form.deptId" placeholder="请选择" clearable filterable size="small" >
                  <el-option
                    v-for="dict in deptList"
                    :key="dict.key"
                    :label="dict.value"
                    :value="dict.key"
                  />
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="状态" prop="status">
              <el-switch
                v-model="form.status"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="校区总人数" prop="personNum">
              <el-input v-model="form.personNum" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="校区描述" prop="schoolDescribe">
              <el-input v-model="form.schoolDescribe" type="textarea" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="校区负责人" prop="personInCharge">
              <el-input v-model="form.personInCharge" placeholder="请输入" type="text" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="负责人电话">
              <el-input v-model="form.mobile" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="校区负责人2" prop="personInCharge2">
              <el-input v-model="form.personInCharge2" placeholder="请输入用户密码" type="text" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="负责人2电话">
              <el-input v-model="form.mobile2" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="有效期" prop="time">
              <el-date-picker
                v-model="form.time"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="16">
            <el-form-item label="排序" prop="sortNum">
              <el-input-number v-model="form.sortNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 详细 -->
    <el-dialog title="详细" :visible.sync="detailOpen" width="600px">
      <el-form ref="form" :model="form" label-width="120px" size="mini">
        <el-row>
          <el-col :span="16">
            <el-form-item label="校区名称：">{{ form.name }}</el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="所在城市：">{{ form.city }}</el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="所在部门：">{{ form.deptId }}</el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="状态：">
              <div v-if="form.status === 1">启用</div>
              <div v-else-if="form.status === 0">关闭</div>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="校区总人数：">{{ form.personNum }}</el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="校区描述：">{{ form.schoolDescribe }}</el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="校区负责人：">{{ form.personInCharge }}</el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="负责人电话：">{{ form.mobile }}</el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="校区负责人2：">{{ form.personInCharge2 }}</el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="负责人2电话：">{{ form.mobile2 }}</el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="有效期：">{{ form.startTime + ' 至 ' +  form.endTime }}</el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="排序：">{{ form.sortNum }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { exportUser } from "@/api/system/user";
import {
  listSchool,
  addSchool,
  getDeptList,
  delSchool,
  getHead,
} from "@/api/pt/school.js";
import { getToken } from "@/utils/auth";
import { areajson } from "@/utils/p_city.js";
areajson.map((item) => {
  item.children.map((i) => {
    delete i.children;
  });
});
export default {
  name: "School",
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 用户表格数据
      tableList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 已有校区所在城市数据
      ownCity: [],
      deptList: [],
      // 城市数据
      cityOptions: areajson,
      // 表单参数
      form: {},
      //详情打开
      detailOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        status: undefined,
        city: undefined,
        deptId: undefined,
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "校区名称不能为空", trigger: "blur" },
        ],
        city: [{ required: true, message: "请选择城市", trigger: "blur" }],
        deptId: [{ required: true, message: "请选择部门", trigger: "blur" }],
        time: [{ required: true, message: "请选择时间", trigger: "blur" }],
        email: [
          { required: true, message: "邮箱地址不能为空", trigger: "blur" },
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        phone: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
    getDeptList().then((res) => {
      this.deptList = res.data.dept || [];
    });
    getHead().then((res) => {
      this.ownCity = res.data.city;
    });
  },
  methods: {
    getCityP(e) {
      // e城市中文名  获取城市的省
      this.cityOptions.map((item) => {
        console.log("children");
        console.log(item.children);
        item.children.map((i) => {
          console.log("i");
          console.log(i);
          if (i.label.indexOf(e) != -1) {
            this.form.cityData = [item.label, i.label];
          }
        });
      });
    },
    cityChange(e) {
      console.log(e);
      this.form.city = e[1];
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listSchool(this.addDateRange2(this.queryParams)).then((response) => {
        this.tableList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },

    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    // 状态修改
    handleStatusChange(row) {
      let text = row.status == 1 ? "启用" : "关闭";
      this.$confirm("确认要" + text + '"' + row.name + '"吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          row.time = [new Date(row.startTime), new Date(row.endTime)];
          return addSchool(row);
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status == 1 ? 1 : 0;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.resetForm("form");
      this.form = {
        id: undefined,
        name: undefined,
        city: undefined,
        cityData: [],
        status: undefined,
        personNum: undefined,
        schoolDescribe: undefined,
        personInCharge: undefined,
        mobile: undefined,
        personInCharge2: undefined,
        mobile2: undefined,
        time: undefined,
        sortNum: undefined,
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      console.log(row);
      this.title = "修改";
      row.time = [new Date(row.startTime), new Date(row.endTime)];
      this.form = row;
      this.getCityP(this.form.city);
      if (type === "详情") {
        this.detailOpen = true;
      } else {
        this.open = true;
      }
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.time) {
            this.form.startTime = this.parseTime(this.form.time[0]);
            this.form.endTime = this.parseTime(
              this.form.time[1],
              "{y}-{m}-{d} {23}:{59}:{59}"
            );
          }
          delete this.form.time;
          if (this.form.id !== undefined) {
            addSchool(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.message);
              }
            });
          } else {
            this.form.id = undefined;
            addSchool(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.message);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const Ids = row.id || this.ids;
      let text = "";
      if (row.siteNum > 0) {
        text = `(该校区下有${row.siteNum}个站点，请谨慎删除)`;
      }
      this.$confirm(
        '是否确认删除校区ID为"' + Ids + '"的数据项?' + text,
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delSchool(Ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有用户数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportUser(queryParams);
        })
        .then((response) => {
          this.fileDownload(response.data, "用户管理.xlsx");
        })
        .catch(function () {});
    },
  },
};
</script>

<style type="text/css">
.dian {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  display: inline-block;
  background: #999;
  margin-right: 6px;
}
.dian_kai {
  background: #46a6ff;
}
</style>
